<template>
  <view class="cart-container">
    <!-- 空购物车状态 -->
    <view class="empty-cart" v-if="!cartList || cartList.length === 0">
      <image src="/static/images/common/empty.png" mode="aspectFit"></image>
      <view class="empty-text">购物车还是空的</view>
      <view class="go-shopping" @click="goShopping">去逛逛</view>
    </view>

    <!-- 购物车有商品状态 -->
    <view class="cart-content" v-else>
      <!-- 商品列表 -->
      <view class="cart-list">
        <!-- 商品项 -->
        <view
          class="cart-item"
          v-for="(item, index) in cartList"
          :key="item.id"
          :data-index="index"
          @touchstart="touchStart"
          @touchmove="touchMove"
          @touchend="touchEnd"
        >
          <view
            class="cart-item-wrapper"
            :style="{ transform: 'translateX(' + item.offsetX + 'px)' }"
          >
            <!-- 选择框 -->
            <view class="item-select" @click="toggleSelect(item)">
              <view
                class="checkbox"
                :class="{ checked: item && item.selected }"
              >
                <text v-if="item && item.selected" class="checkbox-icon"
                  >✓</text
                >
              </view>
            </view>

            <!-- 商品信息 -->
            <view class="item-info">
              <image
                class="item-image"
                :src="item ? item.picUrl : ''"
                mode="aspectFill"
              ></image>
              <view class="item-detail">
                <view class="item-name">{{ item ? item.goodsName : '' }}</view>

                <!-- 商品规格 -->
                <view class="item-spec">
                  <text
                    class="spec-tag"
                    v-for="spec in item.specifications"
                    :key="spec"
                    >{{ spec }}</text
                  >
                </view>

                <!-- 优惠信息 -->
                <view class="item-discount" v-if="item && item.couponName">
                  <text class="discount-tag">{{ item.couponName }}</text>
                </view>

                <view class="item-price-count">
                  <view class="item-price">
                    <text v-if="item.couponPrice > 0" class="price-prefix"
                      >券后</text
                    >
                    <text class="price-symbol">¥</text>
                    <text class="price-value">{{
                      item.actualPrice.toFixed(2)
                    }}</text>
                    <text
                      class="original-price"
                      v-if="item.totalPrice > item.actualPrice"
                      >¥{{ item.totalPrice.toFixed(2) }}</text
                    >
                  </view>

                  <!-- 数量调整 -->
                  <view class="item-count">
                    <view
                      v-if="item && item.showCounter"
                      class="count-controls"
                    >
                      <view
                        class="count-btn minus"
                        @click.stop="decreaseCount(item)"
                        >-</view
                      >
                      <view class="count-value">{{
                        item && item.number ? item.number : 0
                      }}</view>
                      <view
                        class="count-btn plus"
                        @click.stop="increaseCount(item)"
                        >+</view
                      >
                    </view>
                    <view
                      v-else
                      class="count-number"
                      @click.stop="toggleCounter(item)"
                    >
                      x{{ item && item.number ? item.number : 0 }}
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <!-- 删除按钮 -->
          <view class="delete-btn" @click="deleteItem(item)">删除</view>
        </view>
      </view>

      <!-- 底部结算栏 -->
      <view class="cart-footer">
        <view class="select-all" @click="toggleSelectAll">
          <view class="checkbox" :class="{ checked: isAllSelected }">
            <text v-if="isAllSelected" class="checkbox-icon">✓</text>
          </view>
          <text>全选</text>
        </view>

        <view class="total-info" @click="togglePriceDetail">
          <view class="total-price">
            <text>合计：</text>
            <text class="price-symbol">¥</text>
            <text class="price-value">{{
              cartTotal.actualAmount.toFixed(2)
            }}</text>
          </view>
          <view class="discount-info">
            <text v-if="cartTotal.couponPrice > 0"
              >已优惠：¥{{ cartTotal.couponPrice.toFixed(2) }} ^</text
            >
            <text v-else>查看明细 ^</text>
          </view>
          <view
            class="mask"
            v-if="showPriceDetail"
            @click.stop="togglePriceDetail"
          ></view>
          <view class="price-detail" v-if="showPriceDetail">
            <view class="detail-item">
              <text>商品总额：</text>
              <text>¥{{ cartTotal.checkedGoodsAmount.toFixed(2) }}</text>
            </view>
            <view class="detail-item" v-if="cartTotal.couponPrice > 0">
              <text>优惠金额：</text>
              <text class="discount"
                >-¥{{ cartTotal.couponPrice.toFixed(2) }}</text
              >
            </view>
            <view class="detail-item freight-item">
              <view class="freight-label">运费：</view>
              <view class="freight-content">
                <text>¥{{ cartTotal.freightPrice.toFixed(2) }}</text>
                <text
                  v-if="freightConfig.litemall_express_freight_min"
                  class="freight-info"
                >
                  满{{
                    freightConfig.litemall_express_freight_min
                  }}元免运费，不足需付¥{{
                    freightConfig.litemall_express_freight_value
                  }}
                </text>
              </view>
            </view>
            <view class="detail-item">
              <text>实付金额：</text>
              <text class="actual"
                >¥{{ cartTotal.actualAmount.toFixed(2) }}</text
              >
            </view>
          </view>
        </view>

        <view
          class="checkout-btn"
          :class="{ disabled: selectedCount === 0 }"
          @click="checkout"
        >
          <text>结算({{ selectedCount }})</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      cartList: [], // 购物车列表
      cartTotal: {}, // 购物车总计信息
      isAllSelected: false, // 是否全选
      loading: false, // 加载状态
      startX: 0, // 触摸开始位置
      moveX: 0, // 触摸移动位置
      showPriceDetail: false, // 是否显示价格详情
      freightConfig: {} // 运费配置信息
    }
  },
  computed: {
    // 选中的商品数量
    selectedCount() {
      if (
        this.cartTotal &&
        typeof this.cartTotal.checkedGoodsCount === 'number'
      ) {
        return this.cartTotal.checkedGoodsCount
      }

      // 备用计算方法
      let count = 0
      if (!this.cartList || !Array.isArray(this.cartList)) {
        return count
      }

      for (let i = 0; i < this.cartList.length; i++) {
        const item = this.cartList[i]
        if (item && item.selected && item.status === 'normal') {
          count += 1
        }
      }
      return count
    }
  },
  onShow() {
    // 每次显示页面时获取购物车数据和运费配置
    this.getCartList()
    this.getFreightConfig()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.getCartList().then(() => {
      uni.stopPullDownRefresh()
    })
  },
  methods: {
    // 触摸开始事件处理
    touchStart(e) {
      if (e.touches.length === 1) {
        this.startX = e.touches[0].clientX
        this.moveX = 0
      }
    },

    // 触摸移动事件处理
    touchMove(e) {
      if (e.touches.length === 1) {
        // 计算移动距离
        const moveX = e.touches[0].clientX - this.startX
        const index = e.currentTarget.dataset.index
        const item = this.cartList[index]

        if (!item) return

        // 限制左滑距离
        let offsetX = 0
        if (moveX < 0) {
          offsetX = Math.max(-80, moveX)
        }

        // 更新商品的偏移量
        this.$set(item, 'offsetX', offsetX)
      }
    },

    // 触摸结束事件处理
    touchEnd(e) {
      const index = e.currentTarget.dataset.index
      const item = this.cartList[index]

      if (!item) return

      // 根据最终偏移量决定是否显示删除按钮
      if (item.offsetX && item.offsetX < -40) {
        this.$set(item, 'offsetX', -80)
      } else {
        this.$set(item, 'offsetX', 0)
      }
    },

    // 关闭所有滑动状态
    closeAllSwipe() {
      if (!this.cartList || !Array.isArray(this.cartList)) return

      this.cartList.forEach((item) => {
        if (item) {
          this.$set(item, 'offsetX', 0)
        }
      })
    },

    // 获取购物车列表
    async getCartList() {
      // 关闭所有滑动状态
      this.closeAllSwipe()

      this.loading = true
      try {
        // 初始化为空数组，确保 cartList 始终是数组
        this.cartList = []

        const res = await this.$get('cart/index')
        if (res.errno === 0) {
          // 处理购物车列表数据
          if (
            res.data &&
            res.data.cartList &&
            Array.isArray(res.data.cartList)
          ) {
            // 处理每个商品的选中状态，将checked转换为selected
            this.cartList = res.data.cartList.map((item) => {
              return {
                ...item,
                selected: item.checked, // 将API返回的checked转换为selected
                status: 'normal' // 默认状态为normal
              }
            })
          } else {
            this.cartList = []
          }

          // 保存购物车总计信息
          if (res.data && res.data.cartTotal) {
            this.cartTotal = res.data.cartTotal
          }

          this.checkSelectAll()
        } else {
          uni.showToast({
            title: res.errmsg || '获取购物车数据失败',
            icon: 'none'
          })
        }
        this.loading = false
      } catch (error) {
        console.error('获取购物车数据失败', error)
        this.cartList = [] // 出错时设置为空数组
        this.loading = false
        uni.showToast({
          title: '网络错误，请刷新重试',
          icon: 'none'
        })
      }
    },

    // 切换单个商品选中状态
    toggleSelect(item) {
      if (!item) return
      try {
        this.$post('cart/checked', {
          cartIds: [item.id],
          isChecked: item.selected ? 0 : 1
        }).then((res) => {
          if (res.errno === 0) {
            this.getCartList()
          } else {
            uni.showToast({
              title: res.errmsg || '操作失败',
              icon: 'none'
            })
          }
        })
      } catch (error) {
        console.log(error)
      }
    },

    // 切换全选状态
    toggleSelectAll() {
      this.isAllSelected = !this.isAllSelected

      // 更新所有商品的选中状态
      if (!this.cartList || !Array.isArray(this.cartList)) {
        this.cartList = []
        return
      }

      this.$post('cart/checked', {
        isChecked: this.isAllSelected ? 1 : 0,
        cartIds: this.cartList.map((item) => item.id)
      })
        .then((res) => {
          if (res.errno === 0) {
            this.getCartList()
          } else {
            uni.showToast({
              title: res.errmsg || '操作失败',
              icon: 'none'
            })
          }
        })
        .catch((err) => {
          console.error('更新全选状态失败', err)
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          })
        })
    },

    // 检查是否全选
    checkSelectAll() {
      // 检查是否所有商品都被选中
      if (
        !this.cartList ||
        !Array.isArray(this.cartList) ||
        this.cartList.length === 0
      ) {
        this.isAllSelected = false
        return
      }

      this.isAllSelected = this.cartList.every((item) => item && item.selected)
    },

    // 增加商品数量
    increaseCount(item) {
      item.number += 1
      this.updateCartItem(item)
    },

    // 减少商品数量
    decreaseCount(item) {
      if (item.number <= 1) {
        this.deleteItem(item)
        return
      }
      item.number -= 1
      this.updateCartItem(item)
    },

    // 更新购物车商品
    updateCartItem(item) {
      if (!item) return
      this.$post('cart/update', {
        id: item.id,
        number: item.number
      })
        .then((res) => {
          if (res.errno === 0) {
            this.getCartList()
          } else {
            uni.showToast({
              title: res.errmsg || '更新失败',
              icon: 'none'
            })
          }
        })
        .catch((err) => {
          console.error('更新购物车失败', err)
          uni.showToast({
            title: '更新失败',
            icon: 'none'
          })
        })
    },

    // 删除购物车商品
    deleteItem(item) {
      if (!item) return

      uni.showModal({
        title: '提示',
        content: '确定要删除该商品吗？',
        success: (res) => {
          if (res.confirm) {
            this.$post('cart/delete', {
              cartIds: [item.id]
            })
              .then((res) => {
                if (res.errno === 0) {
                  this.getCartList()
                } else {
                  uni.showToast({
                    title: res.errmsg || '删除失败',
                    icon: 'none'
                  })
                }
              })
              .catch((err) => {
                console.error('删除购物车商品失败', err)
                uni.showToast({
                  title: '删除失败',
                  icon: 'none'
                })
              })
              .finally(() => {
                uni.hideLoading()
              })
          }
        }
      })
    },

    // 去结算
    checkout() {
      if (this.selectedCount === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        })
        return
      }

      // 检查是否有异常商品
      let hasAbnormalItems = false
      if (!this.cartList || !Array.isArray(this.cartList)) {
        return
      }

      for (let i = 0; i < this.cartList.length; i++) {
        const item = this.cartList[i]
        if (item && item.selected && item.status !== 'normal') {
          hasAbnormalItems = true
          break
        }
      }

      if (hasAbnormalItems) {
        uni.showToast({
          title: '部分商品无法购买，请重新选择',
          icon: 'none'
        })
        return
      }

      // 跳转到结算页面
      uni.navigateTo({
        url: '/pages/pay/index'
      })
    },

    // 去逛逛
    goShopping() {
      uni.switchTab({
        url: '/pages/home/index'
      })
    },

    // 切换数量控制器显示
    toggleCounter(item) {
      if (!item) return

      // 先关闭所有其他商品的计数器
      if (this.cartList && Array.isArray(this.cartList)) {
        this.cartList.forEach((good) => {
          if (good && good !== item) {
            this.$set(good, 'showCounter', false)
          }
        })
      }

      // 切换当前商品的计数器显示状态
      this.$set(item, 'showCounter', !item.showCounter)
    },

    // 切换价格详情显示
    togglePriceDetail() {
      this.showPriceDetail = !this.showPriceDetail
    },

    // 获取运费配置
    async getFreightConfig() {
      try {
        const res = await this.$get('config/express')
        if (res.errno === 0 && res.data) {
          this.freightConfig = res.data
        }
      } catch (error) {
        console.error('获取运费配置失败', error)
      }
    }
  }
}
</script>

<style lang="scss">
.cart-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx 0rpx 120rpx 0rpx;

  // 空购物车样式
  .empty-cart {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 200rpx;

    image {
      width: 240rpx;
      height: 240rpx;
      margin-bottom: 30rpx;
      opacity: 0.9;
    }

    .empty-text {
      font-size: 28rpx;
      color: #666;
      margin-bottom: 40rpx;
    }

    .go-shopping {
      width: 240rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background: #000;
      color: #fff;
      font-size: 28rpx;
      transition: all 0.2s;

      &:active {
        opacity: 0.9;
      }
    }
  }

  // 自定义复选框样式
  .checkbox {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    border: 2rpx solid #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    transition: all 0.2s;

    &.checked {
      background-color: #000;
      border-color: #000;

      .checkbox-icon {
        color: #fff !important;
        font-size: 24rpx;
        font-weight: bold;
        line-height: 1;
        transform: scale(0.9);
      }
    }
  }

  // 购物车内容样式
  .cart-content {
    .cart-list {
      padding: 0;

      .cart-item {
        display: flex;
        position: relative;
        margin-bottom: 20rpx;
        overflow: hidden;

        .cart-item-wrapper {
          display: flex;
          width: 100%;
          padding: 20rpx;
          background-color: #fff;
          transition: transform 0.2s ease;
          z-index: 1;
        }

        .delete-btn {
          position: absolute;
          top: 0;
          right: 0;
          width: 80px;
          height: 100%;
          background-color: #e74c3c;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 26rpx;
        }

        .item-select {
          padding-top: 60rpx;
          margin-right: 20rpx;
        }

        .item-info {
          flex: 1;
          display: flex;

          .item-image {
            width: 160rpx;
            height: 160rpx;
            border-radius: 4rpx;
            background-color: #f5f5f5;
          }

          .item-detail {
            flex: 1;
            margin-left: 20rpx;

            .item-name {
              font-weight: 800;
              font-size: 28rpx;
              color: #333;
              line-height: 1.4;
              margin-bottom: 10rpx;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
              overflow: hidden;
            }

            .item-spec {
              height: 68rpx;

              .spec-tag {
                font-size: 24rpx;
                color: #666;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                background-color: #f5f5f5;
                margin-right: 10rpx;
              }
            }

            .item-status {
              margin-bottom: 10rpx;

              .status-text {
                font-size: 24rpx;
                padding: 4rpx 10rpx;
                border-radius: 4rpx;

                &.error {
                  color: #ff6b00;
                  background-color: rgba(255, 107, 0, 0.1);
                }
              }
            }

            .item-discount {
              display: flex;
              align-items: center;
              margin-bottom: 10rpx;

              .discount-tag {
                font-size: 22rpx;
                color: #000;
                background-color: rgba(0, 0, 0, 0.05);
                padding: 2rpx 8rpx;
                border-radius: 4rpx;
                margin-right: 10rpx;
              }

              .discount-text {
                font-size: 22rpx;
                color: #666;
              }
            }

            .item-price-count {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-top: 10rpx;

              .item-price {
                color: #000;
                display: flex;
                align-items: baseline;

                .price-prefix {
                  font-size: 22rpx;
                  color: #000;
                  margin-right: 6rpx;
                }

                .price-symbol {
                  font-size: 24rpx;
                }

                .price-value {
                  font-size: 32rpx;
                  font-weight: 500;
                }

                .original-price {
                  font-size: 22rpx;
                  color: #999;
                  text-decoration: line-through;
                  margin-left: 10rpx;
                }
              }

              .item-count {
                display: flex;
                align-items: center;

                .count-number {
                  font-size: 26rpx;
                  color: #666;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                }

                .count-controls {
                  display: flex;
                  align-items: center;
                  background-color: #f5f5f5;
                  border-radius: 4rpx;

                  .count-btn {
                    width: 40rpx;
                    height: 40rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 28rpx;

                    &.minus {
                      color: #999;
                    }

                    &.plus {
                      color: #333;
                    }
                  }

                  .count-value {
                    width: 40rpx;
                    text-align: center;
                    font-size: 26rpx;
                    color: #333;
                  }
                }
              }
            }
          }
        }
      }
    }

    // 底部结算栏
    .cart-footer {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      height: 100rpx;
      background-color: #fff;
      display: flex;
      align-items: center;
      padding: 0 20rpx;
      border-top: 1rpx solid #f0f0f0;
      z-index: 2;

      .select-all {
        display: flex;
        align-items: center;

        .checkbox {
          margin-right: 10rpx;
        }

        text {
          font-size: 26rpx;
          color: #333;
        }
      }

      .total-info {
        flex: 1;
        margin-left: 30rpx;
        position: relative;

        .total-price {
          font-size: 26rpx;
          color: #333;

          .price-symbol {
            color: #000;
            font-size: 24rpx;
          }

          .price-value {
            color: #000;
            font-size: 34rpx;
            font-weight: 500;
          }
        }

        .discount-info {
          font-size: 22rpx;
          color: #999;
          margin-top: 2rpx;
        }

        .price-detail {
          position: fixed;
          bottom: 120rpx;
          left: 50%;
          transform: translateX(-50%);
          background: #fff;
          padding: 30rpx;
          border-radius: 16rpx;
          box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.1);
          z-index: 999;
          width: 550rpx;

          .detail-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 28rpx;
            color: #666;
            margin-bottom: 20rpx;
            padding: 5rpx 0;

            &.freight-item {
              align-items: flex-start;

              .freight-label {
                min-width: 120rpx;
              }

              .freight-content {
                flex: 1;
                text-align: right;

                .freight-info {
                  display: block;
                  font-size: 24rpx;
                  color: #999;
                  margin-top: 8rpx;
                }
              }
            }

            &:last-child {
              margin-bottom: 0;
              padding-top: 20rpx;
              border-top: 2rpx solid #f5f5f5;
              color: #333;
              font-weight: 500;
            }

            .discount {
              color: #000;
              font-size: 28rpx;
            }

            .actual {
              color: #000;
              font-size: 32rpx;
              font-weight: bold;
            }
          }
        }

        .view-detail {
          display: flex;
          align-items: center;
          font-size: 22rpx;
          color: #999;
          margin-top: 4rpx;

          .arrow {
            font-size: 20rpx;
            margin-left: 4rpx;
            transition: transform 0.2s;

            &.arrow-up {
              transform: rotate(180deg);
            }
          }
        }
      }

      .checkout-btn {
        width: 200rpx;
        height: 70rpx;
        background: #000;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        transition: all 0.2s;

        &:active {
          opacity: 0.9;
        }

        &.disabled {
          background: #ccc;
        }
      }
    }
  }

  // 添加遮罩层样式
  .mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: transparent;
    z-index: 100;
  }
}
</style>
